/**
 * Created by ZFL on 2017/12/22.
 */
//购物车
function PageInit(){
    if(com_obj.userId && com_obj.userId>0){
       console.log( $('.all-shop-check').attr('checked'))
        intiShop();
    }else{
        $('.shop-add').hide();
        $('.shop-null').show();
        likeGoods(); //人气单品
        infiniteScrrol(); //人气单品滚动加载
    }
}

//登录过期
function againAccessToken() {
    $.delStorage("userData");
    $.delStorage('userOpenid');
    $.delStorage("yd_wx");
    $.delStorage("yd_AccessTokenIndex");
    $.delStorage("userData");
    $.delStorage("uData");
    $.delStorage("AccessTokenIndex");
    wxAccredit();
}
//点击底部导航  返回首页
//点击底部导航    返回首页
function returnHome(){
    var mallStoreId=0;
    var userTalentId=0;
    if(com_obj.mallStoreId){
        mallStoreId=com_obj.mallStoreId;
    }else{
        mallStoreId= $.getStorage('mallStoreId');
        com_obj.mallStoreId=$.getStorage('mallStoreId');
    }
    if(com_obj.userTalentId){
        userTalentId=com_obj.userTalentId;
    }else{
        userTalentId= $.getStorage('userTalentId');
        com_obj.userTalentId=$.getStorage('userTalentId');
    }
    window.location.href='../../index.html?mallStoreId='+mallStoreId+"&userTalentId="+userTalentId;
}
//购物车详情
var page = 1;
var goodsList;
var pageNum=1;
var pageSize=10;
function intiShop(){
    $.ajaxHandler({
            model: function () {
                var obj = {};
                //obj.noFilter=1;
                //obj.pageNum = page;
                //obj.pageSize = 10;
                obj.userId = com_obj.userId;
                if(com_obj.mallStoreId){
                    obj.mallStoreId=com_obj.mallStoreId;
                }else{
                    obj.mallStoreId= $.getStorage('mallStoreId');
                    com_obj.mallStoreId=$.getStorage('mallStoreId');
                }
                console.log(obj)
                return obj;
            },
            visibleTime: 100,
            approve:true,
            dataType: "json",
            api:'yg_baijiaplatform/mallShoppingCart/selectMoreInfoByUserId',
            success: function (result) {
                //console.log(result);
                if (result.code == 10000) {
                    goodsList= result.data;
                    var data = result.data;
                    if(data.length>0){
                        $('.shop-null').hide();
                        $('.shop-add').show();
                        for(var i=0;i<data.length;i++){
                            data[i]['salePrice']=divideNumber(data[i]['salePrice'],100);
                            data[i]['suggestedPrice']=divideNumber(data[i]['suggestedPrice'],100)
                        }
                        var shoppingList ={};
                        shoppingList.data = data;
                        console.log(shoppingList);
                        console.log(data)
                        var source   = $("#entry-template").html();
                        var template = Handlebars.compile(source);
                        $('.shop-add-box').append(template(shoppingList));
                        //ProductCode();//数量绑定
                    }else{
                        //没有商品
                        if(page==1){
                            $('.shop-null').show();
                            likeGoods(); //人气单品
                            infiniteScrrol(); //人气单品滚动加载
                        }
                    }
                } else if (result.code == 20100) {
                    //$.toast('认证失败，重新登录','text');
                    //登录已过期
                    $('.again-access-token').show();
                }else {
                    YDUI.dialog.toast('异常',1000);
                }

            }
        }
    );
}

//人气单品
function likeGoods(){
    $.ajaxHandler({
            model: function () {
                var obj = {};
                obj.pageNum = pageNum;
                obj.pageSize = pageSize;
                if (com_obj.mallStoreId) {
                    obj.storeId = com_obj.mallStoreId;
                } else {
                    obj.storeId = $.getPara("mallStoreId");
                }
                if (com_obj.userId) {
                    obj.userId = com_obj.userId;
                } else {
                    obj.userId = 0;
                }
                return obj;
            },
            visibleTime: 100,
            visible:'hide',
            dataType: "json",
            api: 'yg_baijiaplatform/goods/goodsHotSales',
            success: function (result) {
                //console.log(result);
                if (result.code == 10000) {
                    var data = result.data.list;
                    if(data.length>0){
                        var html ='';
                        $.each(data,function (index,item) {
                            html +='<li>';
                            html +='<a class="hot-list-item" href="../goods/goods.html?goodsId='+item.goodsId+'">';
                            if(item.goodsImage.toString().indexOf('http:')>-1){
                                html +='    <img alt="" src="'+item.goodsImage+'" class="hot-list-item-img" alt="'+item.name+'">';
                            }else{
                                html +='    <img alt="" src="'+$.imgApi()+''+item.goodsImage+'" class="hot-list-item-img" alt="'+item.name+'">';
                            }
                            html +='    <p class="hot-list-title">'+item.name+'</p>';
                            html +='    <p class="hot-list-hr"></p>';
                            html +='    <p class="hot-list-price"><label>'+parseFloat(divideNumber(item.lowestPrice,100)).toFixed(2)+'</label><span class="r-price"><del><i>￥</i>'+parseFloat(divideNumber(item.suggestedPrice,100)).toFixed(2)+'</del></span></p>';
                            html +='    </a>';
                            html +='    </li>';
                        });
                        $('#hot-list-box-id').append(html);
                        loading = false;
                        $('.weui-infinite-scroll-box').hide();
                    }else{
                        if(loading){
                            $(".weui_tab_bd").destroyInfinite();
                            $('.weui-infinite-scroll-box').remove();
                            YDUI.dialog.toast('加载完啦~',1000);
                            loading = false;
                        }

                    }

                }else {
                   YDUI.dialog.toast('人气品牌异常',1000);
                }

            }
        }
    );
}
//人气单品加载滚动加载
var loading = false;
function  infiniteScrrol(){
    $(".weui_tab_bd").infinite().on("infinite", function () {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        $('.weui-infinite-scroll-box').show();
        setTimeout(function() {
            pageNum++;
            likeGoods();
        }, 1000);
    });
}

//数量绑定--
var decreaseFlag = false;
function  decrease(id){
    //if(decreaseFlag) return;
    //decreaseFlag = true;
    var _this =$('.num-'+id+'');
    var num = parseInt(_this.val());
    if(num !="" && num > 1){
        _this.val(num-1);
        pudateShopNum(id,_this.val());
        sumPrice();
    }else{
        delGoods(id);
    }
}
// 数量绑定++
var increaseFlag = false;
function increase(id){
    if(increaseFlag) return;
    increaseFlag = true;
    var _this =$('.num-'+id+'');
    var num = parseInt(_this.val());
    _this.val(num+1);
    pudateShopNum(id,_this.val());
    sumPrice();
}
//修改购物车数量
function pudateShopNum(id,num){
    $.ajaxHandler({
            model: function () {
                var obj ={};
                obj.productNum=num;
                obj.shoppingCartId = id;
                console.log(obj);
                return obj;
            },
            visibleTime: 100,
            visible:'show',
            approve:true,
            dataType: "json",
            api: 'yg_baijiaplatform/mallShoppingCart/updateShoppingCart',
            success: function (result) {
                //var data = result.data;
                if (result.code == 10000) {
                    decreaseFlag = false;
                    increaseFlag  = false;
                }else {
                    console.log(result);
                    YDUI.dialog.toast('数量修改异常',1000);
                }

            }
        }
    );
}
//删除商品
function delGoods(id){
    if(confirm("确定要删除？")){
        $.ajaxHandler({
                model: function () {
                    var obj ={};
                    obj.shoppingCartId = id;
                    console.log(obj)
                    return obj;
                },
                visibleTime: 100,
                visible:'show',
                approve:true,
                dataType: "json",
                api:'yg_baijiaplatform/mallShoppingCart/deleteShoppingCartById',
                success: function (result) {
                    //var data = result.data;
                    if (result.code == 10000) {
                        YDUI.dialog.toast('删除成功', 'success', 800,function(){
                            var storeGoodsL=$('.shopCartId-'+id+'').parents('.store').find('li').length;   //点击删除商品所在店铺商品的个数
                            console.log(storeGoodsL)
                            if(storeGoodsL==1){
                                $('.shopCartId-'+id+'').parents('.store').remove()
                            }else{
                                $('.shopCartId-'+id+'').remove();
                            }


                            if($('.shop-add-box').children('.store').length == 0){
                                //说明购物车删除完了
                                page = 1;
                                $('.shop-add').hide();
                                $('.shop-null').show();
                                likeGoods();
                                infiniteScrrol(); //人气单品滚动加载
                            }else {
                                sumPrice();
                            }
                        });
                    }else {
                        YDUI.dialog.toast(result.message, 'error', 800);
                    }
                }
            }
        );
    }
}

//去清空失效宝贝
function isClear(){
    if($('.invalid').length==0){
        YDUI.dialog.toast('暂无失效商品',1000)
    }else if(confirm('确定清空失效宝贝')){

            $.each($('.invalid'),function (i,item) {
                cleInvGoods($(this).attr('data-id'))
            });

    }
}
//清空失效宝贝
function cleInvGoods(id){

        $.ajaxHandler({
                model: function () {
                    var obj ={};
                    obj.shoppingCartId = id;
                    console.log(obj)
                    return obj;
                },
                visibleTime: 100,
                visible:'show',
                approve:true,
                dataType: "json",
                api: 'yg_baijiaplatform/shoppingCart/deleteShoppingCartById',
                success: function (result) {
                    //var data = result.data;
                    if (result.code == 10000) {
                            var storeGoodsL=$('.shopCartId-'+id+'').parents('.store').find('li').length;   //点击删除商品所在店铺商品的个数
                            if(storeGoodsL==1){
                                $('.shopCartId-'+id+'').parents('.store').remove()
                            }else{
                                $('.shopCartId-'+id+'').remove();
                            }


                            if($('.shop-add-box').children('.store').length == 0){
                                //说明购物车删除完了
                                page = 1;
                                $('.shop-add').hide();
                                $('.shop-null').show();
                                likeGoods();
                                infiniteScrrol(); //人气单品滚动加载
                            }else {
                                sumPrice();
                            }

                    }else {
                        YDUI.dialog.toast(result.message, 'error', 800);
                    }
                }
            }
        );
}
//全选(店铺相对应的所有商品)
function storeAllCheckGoods(id){
    if($('.'+id+' .storeGoodsAll-shop-check').is(':checked')){
        $.each($("."+id+' input[type="checkbox"][name="shop-check"]'),function (i,item) {
            $(this).prop('checked',true);
        });
    }else{
        $.each($("."+id+' input[type="checkbox"][name="shop-check"]'),function (i,item) {
            $(this).prop('checked',false);
        });
    }


    //选择所有店铺   全选按钮也被选中
    var all = 1;
    $.each($('input[type="checkbox"][name="storeGoodsAll-shop-check"]'),function (i,item) {
        if(!$(this).is(':checked')){
            all = 0;
            $('.all-shop-check').prop('checked',false);
            return;
        }
    });
    if(all){
        $('.all-shop-check').prop('checked',true);
    }
    sumPrice();
}
//全选(选择所有商品)
function allCheckGoods() {
    if($('.all-shop-check').is(':checked')){
        //console.log('全选');
        $.each($('input[type="checkbox"][name="shop-check"]'),function (i,item) {
            $(this).prop('checked',true);
        });

        $.each($('input[type="checkbox"][name="storeGoodsAll-shop-check"]'),function (i,item) {
            $(this).prop('checked',true);
        });
    }else{
        $.each($('input[type="checkbox"][name="shop-check"]'),function (i,item) {
            $(this).prop('checked',false);
        });

        $.each($('input[type="checkbox"][name="storeGoodsAll-shop-check"]'),function (i,item) {
            $(this).prop('checked',false);
        });
    }
    sumPrice();
}
//选中单商品
function checkGoods(id){
    //所有单品被选中    全选按钮也被选中
    var all = 1;
    $.each($('input[type="checkbox"][name="shop-check"]'),function (i,item) {
        if(!$(this).is(':checked')){
            all = 0;
            $('.all-shop-check').attr('checked',false);
            return;
        }
    });
    if(all){
        $('.all-shop-check').prop('checked',true);
    }

    var storeAll=1;
    $.each( $('.shopCartId-'+id).parents('ul').find('input[type="checkbox"][name="shop-check"]'),function (i,item) {
        console.log()
        if(!$(this).is(':checked')){
            storeAll = 0;
            $('.storeGoodsAll-shop-check').prop('checked',false);
            return;
        }
    });
    if(storeAll){
        $('.shopCartId-'+id).parents('ul').find('input[type="checkbox"][name="storeGoodsAll-shop-check"]').prop('checked',true);
    }

    sumPrice();
}
//计算价格总价
function sumPrice(){
    var sumprice = 0;
    $.each($('input[name="shop-check"][type="checkbox"]'),function (index,item) {
        var _this  = $(this);
        //选中
        if(_this.is(':checked')){
            var id  = _this.attr('data-id');
            sumprice += parseFloat($('.price-'+id+'').text()*$('.num-'+id+'').val());
        }
    });
    $('.all-sum-price').text(sumprice.toFixed(2));
}

//立即结算
function clearing(){
    if($("input[name='shop-check']:checked").length<1){
        YDUI.dialog.toast('请先选择商品',1000)
        //alert(111)
    }else{
        var  para = {};
        para.applywelfareId  = 0 ;
        para.userId = com_obj.userId;
        if(com_obj.mallStoreId){
            para.mallStoreId=com_obj.mallStoreId;
        }else{
            para.mallStoreId= $.getStorage('mallStoreId');
            para.mallStoreId=$.getStorage('mallStoreId');
        }

        var array = [];
        console.log($('input[name="shop-check"]:checked'))
        $.each($('input[name="shop-check"]:checked'),function (index,item) {
           var ind=$('input[name="shop-check"]:checked').parents('li').index();
            console.log(index);
            var id = $(this).attr('data-id');
            for(var i=index;i<goodsList.length;i++){
                    if(id==goodsList[i].shoppingCartId){
                        var pobj  = {};
                        pobj.brandId =goodsList[i].brandId;//品牌ID
                        pobj.goodId  = goodsList[i].goodId;//商品ID
                        pobj.inventoryId =goodsList[i].inventoryId;//库存ID
                        pobj.quantity  = parseInt($('.num-'+id+'').val()); //数量
                        var roleid =JSON.parse(window.localStorage.getItem('userData')).roleId;

                        array.push(pobj);
                        console.log(array)
                        //break;
                    }




            }


        });
        para.goodsSimpleVoList = array;
        para.noFilter=1;
        para.reqType =1;//	0:app,1:h5
        console.log(para)
        $.setStorage('goodObject',para);
        if($.isWX() && !$.getStorage("userOpenid")) {
            //获取Code
            $.GetWXCode();
        }else if($.isWX() &&$.getStorage("userOpenid")){
            window.location.href='../pay/goodsPay.html';
        }


    }
}
